package com.admin.controller;

import cn.hutool.core.lang.UUID;
import com.admin.common.constant.Constant;
import com.admin.eneity.R;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Base64;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @author 吴驰明
 * @date 2023/7/18
 * @Description
 */
@RestController
public class CaptchaController {

    @Autowired
    private Producer producer;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/captcha")
    public R captcha() throws Exception{
//        String key = UUID.randomUUID().toString();
        String code= producer.createText();

        System.out.println("code="+code);
        BufferedImage image=producer.createImage(code);
        ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        Base64.Encoder encoder = Base64.getEncoder();
        String str = "data:image/jpeg;base64,";

        String base64Img = str + encoder.encodeToString(outputStream.toByteArray());

        // redisTemplate.opsForValue().set(Constant.CAPTCHA_KEY+key,code,5L,TimeUnit.MINUTES);

        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("captcha",code);
        resultMap.put("base64Img",base64Img);
//        resultMap.put("uuid",key);
        return R.ok(resultMap);
    }


}
